﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Magic.System;

[Injection]
public class ConfigService : IConfigService
{
    /// <summary>
    /// 更新配置项
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Edit(Dictionary<string, dynamic> input)
    {
        var list = await SugarContext.Instance.Queryable<SysConfig>().Where(m => input.Keys.Contains(m.Name)).ToListAsync();
        foreach (var item in list)
        {
            input.TryGetValue(item.Name, out dynamic value);
            if (value is JArray)
            {
                item.Value = JsonConvert.SerializeObject(value);
            }
            else
            {
                item.Value = value;
            }
        }
        await SugarContext.Instance.Updateable<SysConfig>(list).ExecuteCommandAsync();
    }

    public async Task<ConfigListOutPut> GetAll()
    {
        ConfigListOutPut result = new ConfigListOutPut();

        var allList = await SugarContext.Instance.Queryable<SysConfig>().ToListAsync();

        result.ConfigGroup = new JObject();

        var groupArr = JArray.Parse(allList.FirstOrDefault(m => m.Name == "config_group")?.Value);


        foreach (var item in groupArr)
        {
            result.ConfigGroup.Add(item.Value<string>("key"), item.Value<string>("value"));
        }


        result.QuickEntrance = JArray.Parse(allList.FirstOrDefault(m => m.Name == "config_quick_entrance")?.Value);
        result.List = new Dictionary<string, dynamic>();
        foreach (var item in result.ConfigGroup)
        {
            result.List.Add(item.Key, new
            {
                List = allList.Where(m => m.Group == item.Key).ToList(),
                Name = item.Key,
                title = item.Value
            });
        }
        return result;
    }

    public async Task Add(AddConfigInput input)
    {
        if (await SugarContext.Instance.Queryable<SysConfig>().AnyAsync(m => m.Name == input.Name))
        {
            throw new ApiException("变量名已存在");
        }
        var model = input.Adapt<SysConfig>();
        if (!string.IsNullOrWhiteSpace(model.Content))
        {
            var array = new JObject();
            foreach (var item in model.Content.Split('\n'))
            {
                array.Add(item.Split("=")[0], item.Split("=")[1]);
            }
            model.Content = JsonConvert.SerializeObject(array);
        }
        await SugarContext.Instance.Insertable<SysConfig>(model).ExecuteCommandAsync();
    }

    public async Task<string> GetByName(string name)
    {
        return (await SugarContext.Instance.Queryable<SysConfig>().FirstAsync(m => m.Name == name))?.Value;
    }
}
